package com.superlc.ssm.core.shiro.filter;

import com.superlc.ssm.common.util.ProjectUtils;
import com.superlc.ssm.common.util.ResponseUtils;
import com.superlc.ssm.core.shiro.ShiroConst;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author super
 *当用户没有登录或session失效后，是使用FormAuthenticationFilter进行拦截处理的
 *我们可以重写里面的onAccessDenied方法，从而修改重定向。
 */
public class ShiroFormAuthenticationFilter extends FormAuthenticationFilter {

    private static Logger logger = LoggerFactory.getLogger(ShiroFormAuthenticationFilter.class);

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                logger.info("isLogRequestSubmission----接下登陆！");
                return executeLogin(request, response);
            } else {
                //allow them to see the login page ;)
                return true;
            }
        } else {
            logger.info("不是登陆请求！");
            //请求可以通过时直接跳转
            HttpServletRequest req = (HttpServletRequest)request;
            HttpServletResponse resp = (HttpServletResponse) response;
            if(req.getMethod().equals(RequestMethod.OPTIONS.name())) {
                resp.setStatus(HttpStatus.OK.value());
                return true;
            }

            //前端Ajax请求时requestHeader里面带一些参数，用于判断是否是前端的请求
            String ajaxHeader = req.getHeader(ShiroConst.AUTHORIZATION);
            if (ajaxHeader != null || req.getHeader("wkcheck") != null) {
                logger.info("当前请求为ajax请求不会重定向！");
                //前端Ajax请求，则不会重定向
                resp.setHeader("Access-Control-Allow-Origin",  req.getHeader("Origin"));
                resp.setHeader("Access-Control-Allow-Credentials", "true");
                resp.setContentType("application/json; charset=utf-8");
                resp.setCharacterEncoding("UTF-8");
                PrintWriter out = resp.getWriter();
                ProjectUtils.object2Json(ResponseUtils.failed("请重新登录！"),out);
            } else {
                saveRequestAndRedirectToLogin(request, response);
            }
            return false;
        }
    }
}